package com.firewolf.rbac;

import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;

import java.io.OutputStream;
import java.lang.reflect.Field;
import java.util.List;

/**
 * 作者：刘兴
 * 时间:19/2/28
 **/
public class PoiUtils {

    /**
     * 导出数据到excel里面
     *
     * @param os           输出流
     * @param headerTitles 表头
     * @param columns      字段名
     * @param data         数据
     */
    public static void exportToExcel(OutputStream os, List<String> headerTitles, List<String> columns, List data) {

        try {
            Workbook wb = new HSSFWorkbook();  // or new XSSFWorkbook();
            Sheet sheet = wb.createSheet("new sheet");

            Row headerRow = sheet.createRow(0);
            for (int i = 0; i < headerTitles.size(); i++) {
                Cell cell = headerRow.createCell(i);
                cell.setCellValue(headerTitles.get(i));
            }

            for (int i = 0; i < data.size(); i++) {
                Row row = sheet.createRow(i + 1);
                Object da = data.get(i);//数据
                for (int j = 0; j < columns.size(); j++) {
                    Cell c = row.createCell(j);
                    Field field = da.getClass().getDeclaredField(columns.get(j));
                    field.setAccessible(true);
                    Object o = field.get(da);
                    if (o != null)
                        c.setCellValue(o.toString());
                }
            }
            wb.write(os);
        } catch (Exception e) {
            System.out.println("xxx");
            e.printStackTrace();
        }

    }

}
